package com.chenxi;

import java.util.concurrent.locks.ReentrantLock;

/*
void lockInterruptibly()方法的作用是，如果当前线程未被中断，则获取锁定，已被中断则抛异常。
 */

public class MyLockInterr {

    public ReentrantLock lock = new ReentrantLock();

    public void waitMethod(){
        try{
            lock.lockInterruptibly();
            System.out.println("lock begin " + Thread.currentThread().getName());
            Thread.sleep(5000);
            System.out.println("lock end " + Thread.currentThread().getName());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            if (lock.isHeldByCurrentThread()){
                lock.unlock();
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        MyLockInterr myLockInterr = new MyLockInterr();
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                myLockInterr.waitMethod();
            }
        };
        Thread aaa = new Thread(runnable, "aaa");
        Thread bbb = new Thread(runnable, "bbb");
        aaa.start();
        Thread.sleep(500);
        bbb.start();
        bbb.interrupt();
        System.out.println("main end");
    }
}
